import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware

from backend.routers.auth_router import router as auth_router
from backend.routers.detection_router import router as detection_router
from backend.model_core import DualFundusModel

app = FastAPI(title="眼部疾病检测系统后端")

# 跨域配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载路由
app.include_router(auth_router)
app.include_router(detection_router)

@app.get("/")
def root():
    return {"message": "API服务已启动"}

@app.get("/test")
def test():
    import cv2
    model = DualFundusModel("backend/model_core/model.pth")
    left_path = "data/train_dataset_and_mark/Training_Dataset/0_left.jpg"
    right_path = "data/train_dataset_and_mark/Training_Dataset/0_right.jpg"
    age = 45
    sex = 1
    
    # 执行预测
    probabilities = model.predict(cv2.imread(left_path), cv2.imread(right_path), age, sex)
    return {
        "正常": f"{probabilities[0]:.4f}",
        "糖尿病": f"{probabilities[1]:.4f}",
        "青光眼": f"{probabilities[2]:.4f}",
        "白内障": f"{probabilities[3]:.4f}",
        "AMD": f"{probabilities[4]:.4f}",
        "高血压": f"{probabilities[5]:.4f}",
        "近视": f"{probabilities[6]:.4f}",
        "其他疾病/异常 ": f"{probabilities[7]:.4f}",
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8080)